<script setup>
import { ref, onMounted, reactive,watch } from 'vue';
import { useUserStore } from '@/stores/admin';
import { ElMessage } from 'element-plus';
import { updateAdminInfo } from '@/api/admin';
import defaultAvatar from '@/assets/default.png';

const formRef = ref()
const userStore = useUserStore()
const isEditing = ref(false)
const loading = ref(false)

// 使用计算属性确保响应式更新
const formModel = reactive({
  username: '',
  nickname: '',
})

const rules = ref({
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}/,
      message: '昵称长度在2-10个非空字符',
      trigger: 'blur'
    }
  ]
})

watch(() => userStore.user, (newUser) => {
  console.log('👤 用户信息变化，更新表单:', newUser)
  console.log('📝 当前表单数据（更新前）:', formModel)
  
  if (newUser && newUser.username) {
    formModel.username = newUser.username
    formModel.nickname = newUser.nickname || ''
    console.log('✅ 表单数据已更新:', formModel)
  } else {
    console.warn('⚠️ 用户信息为空，跳过表单更新')
  }
}, { immediate: true, deep: true })

// 确保用户信息已加载
onMounted(async () => {
  console.log('🏠 UserProfile 组件挂载')
  console.log('🔍 当前用户信息:', userStore.user)
  
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    loading.value = true
    
    // 如果用户信息为空，尝试获取
    if (!userStore.user.username || !userStore.user.id) {
      console.log('📡 开始获取用户信息...')
      await userStore.getUser()
    }
    
    console.log('✅ 表单数据初始化完成:', formModel)
    
  } catch (error) {
    console.error('❌ 获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败: ' + error.message)
  } finally {
    loading.value = false
  }
})

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

const submitForm = async () => {
  try {
    console.log('💾 开始提交表单...')
    console.log('📝 当前表单数据:', formModel)
    console.log('👤 当前用户信息:', userStore.user)
    
    loading.value = true
    
    // 1. 检查用户状态
    if (!userStore.token) {
      throw new Error('用户未登录')
    }
    
    // 2. 确保用户信息存在
    if (!userStore.user || !userStore.user.id) {
      console.log('🔄 用户信息缺失，尝试获取...')
      await userStore.getUser()
      
      if (!userStore.user || !userStore.user.id) {
        throw new Error('无法获取用户信息，请刷新页面重试')
      }
    }
    
    // 3. 表单验证
    await formRef.value.validate()
    console.log('✅ 表单验证通过')
    
    // 4. 准备提交数据
    const submitData = {
      nickname: formModel.nickname || '',
    }
    
    console.log('📤 提交数据:', submitData)
    
    // 5. 调用 API
    const response = await updateAdminInfo(submitData)
    console.log('📨 API响应:', response.data)
    
    if (response.data.code === '0000') {
      console.log('✅ 更新成功，响应数据:', response.data.data)
      
      // 6. 直接使用响应数据更新本地状态，而不是重新获取
      if (response.data.data) {
        userStore.setUser(response.data.data)
        console.log('✅ 本地状态已更新:', userStore.user)
      } else {
        // 如果响应中没有数据，重新获取
        console.log('🔄 响应无数据，重新获取用户信息...')
        await userStore.getUser()
      }
      
      // 7. 完成提交
      isEditing.value = false
      ElMessage.success('修改成功')
      console.log('✅ 提交流程完成')
    } else {
      throw new Error(response.data.msg || '更新失败')
    }
    
  } catch (error) {
    console.error('❌ 提交失败:', error)
    console.error('❌ 错误详情:', error.response?.data)
    ElMessage.error(error.response?.data?.msg || error.message || '修改失败')
  } finally {
    loading.value = false
  }
}


</script>

<template>
  <div class="profile-container">
    <el-card v-loading="loading">
      <div class="card-header">
        <h2>个人资料</h2>
        <el-button 
          type="primary" 
          size="small" 
          @click="isEditing ? submitForm() : toggleEdit()"
          :disabled="loading"
        >
          {{ isEditing ? '保存' : '编辑' }}
        </el-button>
      </div>
      
      <el-form 
        label-width="120px" 
        class="profile-form" 
        ref="formRef" 
        :model="formModel"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="formModel.username" 
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="formModel.nickname" 
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.profile-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .profile-form {
    margin-top: 20px;
  }
}
</style>